<template>
  <a-card :bordered="false" title="发布商品" style="min-height: 100vh">
    <a-row style="width: 100%; ">
      <a-steps :current="current" style="width: 80%;margin: auto">
        <a-step v-for="(item,index) in steps" :key="index" :title="item" />
      </a-steps>
    </a-row>
    <div v-if="!loading">
      <spu-info v-show="current === 0" ref="spuModel" v-model="spuModel" @next="next"></spu-info>
      <spec-info v-show="current === 1" ref="specModel" v-model="specModel" @prev="prev" @next="next"></spec-info>
      <sale-info v-show="current === 2" ref="saleModel" v-model="saleModel" @prev="prev" @next="next"></sale-info>
      <sku-info v-show="current === 3" ref="skuModel" v-model="skuModel" @prev="prev" @submit="submit"></sku-info>
    </div>
    <div style="display: flex;justify-content: center" v-else>
      <a-spin size="large" />
    </div>
  </a-card>
</template>
<script>
import SkuInfo from './product/SkuInfo.vue'
import SpecInfo from './product/SpecInfo.vue'
import SaveComplete from './product/SaveComplete.vue'
import SaleInfo from './product/SaleInfo.vue'
import SpuInfo from './product/SpuInfo.vue'
import { getAction, postAction } from '../../api/manage'

export default {
  components: { SkuInfo, SpuInfo, SpecInfo, SaveComplete, SaleInfo },
  watch: {
    specModel: {
      handler(val) {
        this.specModel = val
      },
      deep: true
    },
    spuModel: {
      handler(val) {
        this.spuModel = val
      },
      deep: true
    },
    saleModel: {
      handler(val) {
        this.saleModel = val
      },
      deep: true
    },
    skuModel: {
      handler(val) {
        this.skuModel = val
      },
      deep: true
    }
  },
  created() {

  },
  data() {
    return {
      current: 0,
      steps: ['基本信息', '规格参数', '销售属性', 'SKU信息'],
      loading: false,
      url: {
        initSpecList: '/product/attrGroup/initSpecList',
        initMemberList: '/member/memberLevel/list',
        addSpu: '/product/spuInfo/addSpu'
      },
      spuModel: {
        spuName: '',
        spuDescription: '',
        catalogId: 225,
        brandId: undefined,
        weight: '',
        publishStatus: '',
        buyBounds: '',
        growBounds: '',
        description: '',
        images: '',
        memberList: []
      },
      specModel: {
        catalogId: '',
        specList: []
      },
      saleModel: {
        catalogId: '',
        specList: []
      },
      skuModel: {}
    }
  },
  methods: {
    /**
     * 初始化会员等级列表
     */
    initMemberList() {
      getAction(this.url.initMemberList, { pageNo: 1, pageSize: 10000 }).then(res => {
        if (res.success) {
          this.spuModel.memberList = res.result.records
        } else {
          this.$message.error('获取会员等级列表失败!')
        }
      })
    },
    /**
     * 下一步
     */
    next() {
      switch (this.current) {
        case 0:
          this.$refs.specModel.initCategoryId(this.spuModel.catalogId)
          break
        case 1:
          this.$refs.saleModel.initCategoryId(this.spuModel.catalogId)
          break
        case 2:
          this.initMemberList()
          let form = {
            saleModel: this.saleModel,
            spuModel: this.spuModel
          }
          this.$refs.skuModel.initSkuTable(form)
          break
        default:
      }
      this.current++
    },
    /**
     * 上一步
     */
    prev() {
      this.current--
    },
    /**
     * 提交表单
     */
    submit() {
      this.loading = true
      let params = {}
      params.spuInfo = this.spuModel
      params.specList = this.createSpecList()
      params.saleList = this.createSaleList()
      params.skuList = this.createSkuList()
      postAction(this.url.addSpu, params).then(res => {
        if (res.success) {
          this.$message.success('保存成功！')
        } else {
          this.$message.error('保存失败!')
        }
      }).finally(()=>{
        this.loading = false
      })
    },
    /**
     * 创建规格列表
     * @returns {*[]}
     */
    createSpecList() {
      let specList = []
      for (let item of this.specModel.specList) {
        for (let spec of item.attributeList) {
          let value = spec.specValue
          if (value != null && value != undefined) {
            if (typeof value === 'string') {
              specList.push({
                attrId: spec.id,
                attrName: spec.attrName,
                specValue: value
              })
            } else {
              specList.push({
                attrId: spec.id,
                attrName: spec.attrName,
                specValue: value.join(',')
              })
            }
          }
        }
      }
      return specList
    },
    /**
     * 创建销售属性列表
     * @returns {*[]}
     */
    createSaleList() {
      let list = []
      for (let item of this.saleModel.specList) {
        let value = item.specValue
        if (typeof value === 'string') {
          list.push({
            attrId: item.id,
            attrName: item.attrName,
            specValue: value
          })
        } else {
          value.forEach(it => {
            list.push({
              attrId: item.id,
              attrName: item.attrName,
              specValue: it
            })
          })
        }
      }
      return list
    },
    /**
     * 创建sku列表
     * @returns {*[]}
     */
    createSkuList() {
      let list = this.$refs.skuModel.dataSource
      let skuList = []
      list.forEach(item => {
        const numericKeyObject = Object.keys(item)
          .filter(key => !isNaN(Number(key)))  // 筛选出数字类型的key
          .reduce((acc, key) => {
            acc[key] = item[key]  // 创建一个新对象，包含数字类型的key
            return acc
          }, {})
        skuList.push({
          skuName: item.skuName,
          skuTitle: item.skuTitle,
          skuSubtitle: item.skuSubtitle,
          price: item.price,
          images: item.images,
          discount: item.discount,
          discountItem: item.discountItem,
          discountOffers: item.discountOffers,
          full: item.full,
          fullItem: item.fullItem,
          fullOffers: item.fullOffers,
          memberList: item.memberList,
          specModel: JSON.stringify()
        })
      })
      return skuList
    }
  }
}
</script>
<style>
</style>
